<template>
  <div>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="单据类型" prop="documentType">
        <el-select
          v-model="queryParams.documentType"
          placeholder="请选择单据类型"
          clearable
          style="width: 240px"
          @change="handleQuery"
        >
          <el-option
            v-for="dict in dict.type.doc_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ruleSetting:docConfig:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ruleSetting:docConfig:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ruleSetting:docConfig:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="rulesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center">
        <template slot-scope="scope">
          {{( queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}
        </template>
      </el-table-column>
      <el-table-column label="单据类型" align="center" prop="documentType">
        <template slot-scope="scope">
          <el-tag type="primary"><dict-tag :options="dict.type.doc_type" :value="scope.row.documentType"/></el-tag>
        </template>
      </el-table-column>
      <el-table-column label="编码分段" align="center" prop="codeSegment" />
      <el-table-column label="段间分隔符" align="center" prop="separator">
        <template #default="{row}">
          <dict-tag :options="dict.type.encode_separator" :value="row.separator"/>
        </template>
      </el-table-column>
      <el-table-column label="应用规则" align="center" prop="applicationRule">
        <template #default="{row}">
          <span v-if="row.applicationRule === '01'">新增显示且允许修改</span>
          <span v-if="row.applicationRule === '02'">新增显示且不允许修改</span>
        </template>
      </el-table-column>
      <el-table-column label="常量记录" align="center" prop="constRecord" />
      <el-table-column label="单据日期格式" align="center" prop="dateFormat" />
      <el-table-column label="流水号长度" align="center" prop="serialNumLength" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ruleSetting:docConfig:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ruleSetting:docConfig:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改单据规则对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :span="24">
          <el-col :span="12">
            <el-form-item label="单据类型" prop="documentType">
              <el-select
                v-model="form.documentType"
                placeholder="请选择单据类型"
                clearable
                style="width: 240px"
              >
              <template v-if="form.id">
                <el-option
                  v-for="dict in dict.type.doc_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </template>
              <template v-else>
                <el-option
                  v-for="item in docTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </template>
            </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="编码分段" prop="codeSegment">
              <el-select v-model="form.codeSegment" clearable placeholder="请选择编码分段">
                <el-option
                  v-for="item in codeSegments"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :span="24">
          <el-col :span="12">
            <el-form-item label="段间分隔符" prop="separator">
              <el-select
                v-model="form.separator"
                placeholder="请选择段间分隔符"
                clearable
                style="width: 240px"
              >
                <el-option
                  v-for="dict in dict.type.encode_separator"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="应用规则" prop="applicationRule">
              <el-select v-model="form.applicationRule" clearable placeholder="请选择应用规则" >
                <el-option
                  v-for="item in applicationRules"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <div class="tab-title">
            编码一段
          </div>
          <el-form-item label="编码一段" prop="encode1">
            <el-select v-model="form.encode1" clearable placeholder="选择编码一段" >
              <el-option
                v-for="item in encodeType1"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设置值" prop="constRecord" v-if="form.encode1 === '01'">
            <el-input v-model="form.constRecord" placeholder="请设置值" />
          </el-form-item>
          <el-form-item label="日期格式" prop="dateFormat" v-if="form.encode1 === '02'">
            <el-input v-model="form.dateFormat" placeholder="请选择日期格式" />
          </el-form-item>
        </el-row>
        <el-row>
          <div class="tab-title">
            编码二段
          </div>
          <el-form-item label="编码二段" prop="encode2">
            <el-select v-model="form.encode2" clearable placeholder="选择编码二段" v-if="form.codeSegment === 3">
              <el-option
                v-for="item in encodeType1"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled">
              </el-option>
            </el-select>
            <el-select v-model="form.encode2" clearable placeholder="选择编码二段" v-else>
              <el-option
                label="流水号"
                value="03">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设置值" prop="constRecord" v-if="form.encode2 === '01'">
            <el-input v-model="form.constRecord" placeholder="请设置值" />
          </el-form-item>
          <el-form-item label="日期格式" prop="dateFormat" v-if="form.encode2 === '02'">
            <el-select
              v-model="form.dateFormat"
              placeholder="请选择日期格式"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="dict in dict.type.rule_date_format"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="流水号长度" prop="serialNumLength" v-if="form.encode2 === '03'">
            <el-input v-model="form.serialNumLength" placeholder="请选择流水号长度" />
          </el-form-item>
        </el-row>
        <el-row  v-if="form.codeSegment && form.codeSegment > 2">
          <div class="tab-title">
            编码三段
          </div>
          <el-form-item label="编码三段" prop="encode3">
            <el-select v-model="form.encode3" clearable placeholder="选择编码三段" >
              <el-option
                v-for="item in encodeType2"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设置值" prop="constRecord" v-if="form.encode3 === '01'">
            <el-input v-model="form.constRecord" placeholder="请设置值" />
          </el-form-item>
          <el-form-item label="日期格式" prop="dateFormat" v-if="form.encode3 === '02'">
            <el-select
              v-model="form.dateFormat"
              placeholder="请选择日期格式"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="dict in dict.type.rule_date_format"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="流水号长度" prop="serialNumLength" v-if="form.encode3 === '03'">
            <el-select v-model="form.serialNumLength" clearable  placeholder="请选择流水号长度">
              <el-option
                v-for="number in numbersToDisplay"
                :key="number"
                :label="number"
                :value="number"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRules, getRules, delRules, addRules, updateRules } from "@/api/basicData/ruleSetting/docConfig.js";

export default {
  name: "DocConfig",
  dicts: ['rule_date_format', 'doc_type', 'encode_separator'],
  props: {
    show: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 单据规则表格数据
      rulesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        documentType: null
      },
      codeSegments: [
        {
          label: '2',
          value: 2
        },
        {
          label: '3',
          value: 3
        }
      ],
      separators: [
        {
          label: '-',
          value: '01',
        },
        {
          label: '_',
          value: '02',
        },
        {
          label: '无',
          value: '03',
        },
      ],
      applicationRules: [
        {
          label: '新增显示且允许修改',
          value: '01',
        },
        {
          label: '新增显示且不允许修改',
          value: '02',
        }
      ],
      encodeType1: [
        {
          label: '常量',
          value: '01',
          disabled: false
        },
        {
          label: '单据日期',
          value: '02',
          disabled: false
        }
      ],
      encodeType2: [
        {
          label: '常量',
          value: '01',
          disabled: false
        },
        {
          label: '单据日期',
          value: '02',
          disabled: false
        },
        {
          label: '流水号',
          value: '03',
          disabled: false
        }
      ],
      numbersToDisplay: [3, 4, 5],
      // 表单参数
      form: {
        id: null,
        documentType: null,
        codeSegment: 3,
        separator: '03',
        applicationRule: '01',
        encode1: null,
        encode2: null,
        encode3: null,
        constRecord: null,
        dateFormat: null,
        serialNumLength: 5
      },
      docTypeList: [],
      // 表单校验
      rules: {
        documentType: [
          { required: true, message: "单据类型不能为空", trigger: "blur" }
        ],
        codeSegment: [
          { required: true, message: "编码分段不能为空", trigger: "blur" }
        ],
        separator: [
          { required: true, message: "段间分割不能为空", trigger: "blur" }
        ],
        applicationRule: [
          { required: true, message: "应用分段不能为空", trigger: "blur" }
        ],
        encode1: [
          { required: true, message: "编码分段一不能为空", trigger: "blur" }
        ],
        encode2: [
          { required: true, message: "编码分段二不能为空", trigger: "blur" }
        ],
        encode3: [
          { required: true, message: "编码分段三不能为空", trigger: "blur" }
        ],
        constRecord: [
          { required: true, message: "常量不能为空", trigger: "blur" }
        ],
        dateFormat: [
          { required: true, message: "日期格式不能为空", trigger: "blur" }
        ],
        serialNumLength: [
          { required: true, message: "流水号长度不能为空", trigger: "blur" }
        ]
      }
    };
  },
  watch: {
    show: {
      handler(newVal, oldVal) {
        if(newVal) {
          this.getList()
        }
      }
    },
    'form.codeSegment': {
      immediate: true,
      handler(newVal, oldVal) {
        if(this.title === "修改单据规则") return
        this.form.encode1 = null
        this.form.encode2 = null
        this.form.encode3 = null
        this.form.constRecord = null
        this.form.dateFormat = null
        this.form.serialNumLength = null
      }
    },
    'form.encode1': {
      immediate: true,
      handler(newVal, oldVal) {
        this.checkEncode(newVal, oldVal)
      }
    },
    'form.encode2': {
      immediate: true,
      handler(newVal, oldVal) {
        this.checkEncode(newVal, oldVal)
      }
    },
    'form.encode3': {
      immediate: true,
      handler(newVal, oldVal) {
        this.checkEncode(newVal, oldVal)
      }
    }
  },

  created() {
    this.getList();
  },
  methods: {
    checkEncode(newVal, oldVal) {
      if(this.title === "修改单据规则") return
      if(oldVal === '01') {
        this.form.constRecord = null
      } else if(oldVal === '02') {
        this.form.dateFormat = null
      }else if(oldVal === '03') {
        this.form.serialNumLength = null
      }

      // 遍历数组找到包含指定值的对象
      for (let i = 0; i < 2; i++) {
        if (newVal && this.encodeType1[i].value === newVal) {
          // 修改找到的对象的属性值
          this.$set(this.encodeType1[i], 'disabled', true)
          this.$set(this.encodeType2[i], 'disabled', true)
          break; // 找到后可以跳出循环
        }
        if (oldVal && this.encodeType1[i].value === oldVal) {
          this.$set(this.encodeType1[i], 'disabled', false)
          this.$set(this.encodeType2[i], 'disabled', false)
        }
      }
      if (newVal && this.encodeType2[2].value === newVal) {
        // 修改找到的对象的属性值
        this.$set(this.encodeType2[2], 'disabled', true)
      }
      if (oldVal && this.encodeType2[2].value === oldVal) {
        this.$set(this.encodeType2[2], 'disabled', false)
      }
    },
    /** 查询单据规则列表 */
    getList() {
      this.loading = true;
      listRules(this.queryParams).then(response => {
        this.rulesList = response.rows;
        this.total = response.total;
        this.initDict();
        this.loading = false;
      });
    },
    initDict() {
      this.docTypeList = []
      let map = []
      for(let rules of this.rulesList) {
        map[rules.documentType] = 1
      }
      for(let item of this.dict.type.doc_type) {
        if (map[item.value] !== 1){
          this.docTypeList.push({
            label: item.label,
            value: item.value,
          })
        }
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        documentType: null,
        codeSegment: 3,
        separator: '03',
        applicationRule: '01',
        encode1: null,
        encode2: null,
        encode3: null,
        constRecord: null,
        dateFormat: null,
        serialNumLength: 5
      };
      this.resetForm("form");
      this.encodeType1 = [
        {
          label: '常量',
          value: '01',
          disabled: false
        },
        {
          label: '单据日期',
          value: '02',
          disabled: false
        }
      ],
      this.encodeType2 = [
        {
          label: '常量',
          value: '01',
          disabled: false
        },
        {
          label: '单据日期',
          value: '02',
          disabled: false
        },
        {
          label: '流水号',
          value: '03',
          disabled: false
        }
      ]
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加单据规则";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.title = "修改单据规则";
      this.reset();
      const id = row.id || this.ids
      getRules(id).then(response => {
        let data = response.data
        let encodeJoinSequenceString = data.encodeJoinSequence
        this.form = data;

        // 使用 split 方法将字符串拆分成数组
        const encodeJoinSequenceArray = (encodeJoinSequenceString || '').split(',');

        for (let index = 0; index < encodeJoinSequenceArray.length; index++) {
          let field = 'encode' + (index + 1);
          this.$set(this.form, field, encodeJoinSequenceArray[index]);
        }

        this.open = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let encodeJoinSequenceString = ''
          if(this.form.encode1) {
            encodeJoinSequenceString += this.form.encode1 + ","
          }
          if(this.form.encode2) {
            encodeJoinSequenceString += this.form.encode2 + ","
          }
          if(this.form.encode3) {
            encodeJoinSequenceString += this.form.encode3 + ","
          }
          encodeJoinSequenceString = encodeJoinSequenceString
                  .substring(0,encodeJoinSequenceString.length-1)
          this.form.encodeJoinSequence = encodeJoinSequenceString
          if (this.form.id != null) {
            updateRules(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRules(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除单据规则编号为"' + ids + '"的数据项？').then(function() {
        return delRules(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/rules/export', {
        ...this.queryParams
      }, `rules_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style>
.tab-title{
  margin-left: 30px;
  padding-left: 15px;
  margin-bottom: 15px;
  border-left: 5px solid #1890ff;
  font-size: 18px;
  font-weight: 600;
}
</style>